package com.example.pandaso.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.pandaso.engines.BaseEngine;
import com.example.pandaso.factory.EngineFactroy;
import com.example.pandaso.pojo.ChatOutputRequest;
import com.example.pandaso.pojo.JwtResponse;
import com.example.pandaso.pojo.LoginRequest;
import com.example.pandaso.pojo.User;
import com.example.pandaso.pojo.UserPassword;
import com.example.pandaso.service.impl.UserService;
import com.example.pandaso.utils.JwtUtils;
import com.example.pandaso.utils.ResponseUtils;

// 用户操作相关的controller
@RestController
@RequestMapping("/api")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private EngineFactroy engineFactroy;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        // 验证用户名和密码
        if (userService.isValidUser(loginRequest.getUsername(), loginRequest.getPassword())) {
            // 生成JWT令牌
            String token = jwtUtils.generateToken(loginRequest.getUsername());
            // 将令牌返回给客户端
            return ResponseUtils.ok(new JwtResponse(token));
        } else {
            return ResponseUtils.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "数据异常");
        }
    }

    @GetMapping("/tips/{engineName}")
    public ResponseEntity<?> getTips(@PathVariable String engineName, @RequestParam String keyword) {
        BaseEngine engine = engineFactroy.getEngine(engineName);
        if (engine == null) {
            return ResponseUtils.error(HttpStatus.NOT_FOUND, "不支持的搜索引擎" + engineName);
        }
        return ResponseUtils.ok(engine.getTips(keyword));
    }

    @GetMapping("/user-engines")
    public ResponseEntity<?> getUserEngines(@RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);
        // 根据用户Id 获得用户自定义引擎数据
        return ResponseUtils.ok(userService.findEnginesByUserId(userId));
    }

    @GetMapping("/user-info")
    public ResponseEntity<?> getUserIfo(@RequestHeader String token) {

        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户信息
        User user = userService.findUserInfoByUserName(username);
        if (user == null) {
            return ResponseUtils.error(HttpStatus.NOT_FOUND, username);
        } else {
            return ResponseUtils.ok(user);
        }
    }

    @PostMapping("/enroll")
    public ResponseEntity<?> enroll(@RequestBody User user) {
        // 判断用户是否存在
        if (userService.isValiName(user.getUsername())) {
            // 判断email是否已经注册
            if (userService.isValiEmail(user.getUsermail())) {
                if (userService.isEnroll(user)) {
                    return ResponseUtils.ok(HttpStatus.CREATED);
                } else {
                    return ResponseUtils.error(HttpStatus.BAD_REQUEST, "注册失败");
                }
            } else {
                return ResponseUtils.error(HttpStatus.CONFLICT, "邮箱已经注册");
            }
        } else {
            return ResponseUtils.error(HttpStatus.CONFLICT, "用户名存在");
        }
    }

    @PostMapping("/update-userengines")
    public ResponseEntity<?> updateUserEngines(@RequestBody Map<String, Boolean> userEngines,
            @RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);
        // 更新用户自定义引擎
        int updatecount = userService.updateUserEngines(userEngines, userId);
        return ResponseUtils.ok(updatecount);

    }

    @PostMapping("/update-user-chatoutput")
    public ResponseEntity<?> updateUserChatOutput(@RequestBody String chatOutput, @RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);
        int isUpdate = userService.updateUserChatoutPut(chatOutput, userId);
        return ResponseUtils.ok(isUpdate);

    }

    @GetMapping("/user-chatoutput")
    public ResponseEntity<?> getUserChatOutput(@RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);
        ChatOutputRequest chatoutput = userService.getUserChatOutput(userId);
        return ResponseUtils.ok(chatoutput);
    }

    @PostMapping("/update-userpassword")
    public ResponseEntity<?> updateUserpassword(@RequestBody UserPassword userPassword, @RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);
        int isupdate = userService.updateUserPassword(userPassword.getUserpassword(), userId);
        System.out.println(isupdate);
        if (isupdate == -1) {
            return ResponseUtils.error(HttpStatus.NOT_ACCEPTABLE, "修改失败");
        } else {
            return ResponseUtils.ok("同步成功");
        }
    }

    @PostMapping("/login_Time")
    public ResponseEntity<?> updateLoginTime(@RequestBody String loginTime, @RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);
        // 更新表
        Boolean isTime = userService.findLoginTime(userId, loginTime);

        return ResponseUtils.ok(isTime);
    }

    @PostMapping("/login_History")
    public ResponseEntity<?> getLoginTime(@RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);

        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);
        // 获取表
        List<String> loginTimes = userService.findLoginHistory(userId);

        return ResponseUtils.ok(loginTimes);
    }

    @PostMapping("/user_search")
    public ResponseEntity<?> updateSearch(@RequestBody Map<String, Object> requestBody, @RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);
        // 更新表
        String search = (String) requestBody.get("search");
        Boolean isTime = userService.findSearch(userId, search);
        return ResponseUtils.ok(isTime);
    }

    @GetMapping("/user-saveSearch")
    public ResponseEntity<?> getUsersaveSearch(@RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);
        List<String> search = userService.findsaveSearch(userId);
        return ResponseUtils.ok(search);
    }

    @PostMapping("/user_deletesearch")
    public ResponseEntity<?> deletesaveSearch(@RequestHeader String token) {
        // 解析JWT令牌，获取用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 根据用户名，查找用户id
        int userId = userService.findUserIdByuserName(username);

        Boolean search = userService.deleteSearch(userId);
        return ResponseUtils.ok(search);
    }
}
